package cn.zhikaizhang.indexviewdemo.demo2;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import cn.zhikaizhang.indexview.Binder;
import cn.zhikaizhang.indexview.IndexView;
import cn.zhikaizhang.indexview.PinYinUtil;
import cn.zhikaizhang.indexview.PinyinComparator;
import cn.zhikaizhang.indexviewdemo.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class MyContactActivity extends Activity implements AdapterView.OnItemClickListener {
  private static SimpleDateFormat mFormatter = new SimpleDateFormat("mm:ss");
  private View mContainer;
  private ListView listView;
  private IndexView indexView;
  private List<ContactInfo> list = new ArrayList<>();
  private ContactAdapter mAdapter;
  private QueryTask mTask;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo2);
    mContainer = findViewById(R.id.container);
    listView = (ListView) findViewById(R.id.listview);
    mAdapter = new ContactAdapter(this);
    listView.setAdapter(mAdapter);
    listView.setOnItemClickListener(this);
    EditText editText = (EditText) findViewById(R.id.et_query);
    editText.addTextChangedListener(new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override public void afterTextChanged(Editable s) {
        mAdapter.setDatas(fuzzyQuery(list, s.toString()));
      }
    });

    indexView = (IndexView) findViewById(R.id.indexView);
    new Binder(listView, indexView) {
      @Override public String getListItemKey(int position) {
        return mAdapter.getItem(position).name;
      }
    }.bind();
    // TODO loading
    mTask = new QueryTask();
    mTask.execute();
  }

  // 支持姓名、全拼、首字母，电话
  public List<ContactInfo> fuzzyQuery(List<ContactInfo> list, String str) {
    List<ContactInfo> infos = new ArrayList<>();
    for (ContactInfo info : list) {
      if (info.fuzzyQuery(str)) {
        infos.add(info);
      }
    }
    return infos;
  }

  private String format() {
    return mFormatter.format(new Date(System.currentTimeMillis()));
  }

  /*
   * 自定义显示Contacts提供的联系人的方法
   */
  public void queryContacts() {
    ContentResolver contentResolver = getContentResolver();

    // 这里只查询指定的列
    String[] projection = {
        ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts._ID,
        ContactsContract.Contacts.HAS_PHONE_NUMBER, ContactsContract.Contacts.SORT_KEY_PRIMARY,
    };

    // Uri.parse("content://com.android.contacts/contacts"
    // 获得所有的联系人, 按照sort_key升序查询
    Log.i("fcy", "----------------- query into curstor start .." + format());
    Cursor cursor =
        contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
    Log.i("fcy", "----------------- query into curstor end .." + format());
    // 循环遍历
    if (cursor != null && cursor.moveToFirst()) {
      int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
      int displayNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

      do {
        // 获得联系人的ID
        String contactId = cursor.getString(idColumn);
        // 获得联系人姓名
        String displayName = cursor.getString(displayNameColumn);
        ContactInfo contactInfo = new ContactInfo();
        contactInfo.name = displayName;
        contactInfo.pinyin = PinYinUtil.toPinyin(displayName);
        contactInfo.jianpin = PinYinUtil.toJianPin(displayName);
        list.add(contactInfo);

        // 查看联系人有多少个号码，如果没有号码，返回0
        int phoneCount =
            cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

        if (phoneCount > 0) {
          List<String> phones = new ArrayList<>();
          // 获得联系人的电话号码列表
          Cursor phoneCursor =
              getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                  ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
          if (phoneCursor != null && phoneCursor.moveToFirst()) {
            do {
              //遍历所有的联系人下面所有的电话号码
              String phoneNumber = phoneCursor.getString(
                  phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              phones.add(phoneNumber);
            } while (phoneCursor.moveToNext());
          }
          contactInfo.phones = phones;
        }
      } while (cursor.moveToNext());
    }
  }

  @Override protected void onDestroy() {
    if (mTask != null) mTask.cancel(true);
    super.onDestroy();
  }

  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(this, list.get(position).toString(), 1).show();
  }

  private class QueryTask extends AsyncTask<Void, Void, Void> {

    @Override protected Void doInBackground(Void... params) {
      queryContacts();
      Log.i("fcy", "----------------- queryContacts end .." + format());
      Collections.sort(list, new PinyinComparator<ContactInfo>() {
        @Override public int compare(ContactInfo s1, ContactInfo s2) {
          return compare(s1.name, s2.name);
        }
      });
      Log.i("fcy", "----------------- sort end .." + format());
      return null;
    }

    @Override protected void onPostExecute(Void aVoid) {
      if (list != null && list.size() > 0 && mAdapter != null) {
        mAdapter.setDatas(list);
        mContainer.setVisibility(View.VISIBLE);
      }
      // TODO 关闭loading
    }
  }
}
